package ita.class1.group2.supermarket.common.captain.model;

import ita.class1.group2.supermarket.common.util.RegexUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Path {

    private static final String PATH_REGEX = "^/\\w*(/\\w+)*";
    private static final String PATH_VARIABLES_REGEX = "(\\{(\\w+)\\})+";
    private static final String URI_PATH_VARIABLES_REGEX = "/[\\w\\.]*";

    private String path;
    private List<String> pathVariables;

    public Path(String path) {
        this.path = RegexUtil.match(PATH_REGEX, path).get(0);
        this.pathVariables = RegexUtil.match(PATH_VARIABLES_REGEX, path);
        for (int i=0; i<this.pathVariables.size(); i++) {
            this.pathVariables.set(i, this.pathVariables.get(i).substring(1, this.pathVariables.get(i).length()-1));
        }
    }

    public String getPath() {
        return path;
    }

    public List<String> getPathVariables() {
        return pathVariables;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Path path1 = (Path) o;
        return Objects.equals(path, path1.path);
    }

    @Override
    public int hashCode() {
        return Objects.hash(path);
    }

    @Override
    public String toString() {
        return "path: " + this.path + ", path variables: " + this.pathVariables;
    }

    public boolean checkURI(String requestURI, String contextPath) {
        if (requestURI.substring(contextPath.length()).startsWith(this.path)) {
            if (RegexUtil.match(URI_PATH_VARIABLES_REGEX, requestURI.substring(contextPath.length()).substring(this.getPath().length())).size() == this.pathVariables.size()) {
                return true;
            }
        }
        return false;
    }

    public static Map<String, String> getPathVariables(Path path, String requestURI, String contextPath) {
        Map<String, String> variables = new HashMap<String, String>();
        if (path != null && requestURI != null && path.checkURI(requestURI, contextPath)) {
            List<String> temps = RegexUtil.match(URI_PATH_VARIABLES_REGEX, requestURI.substring(contextPath.length()).substring(path.getPath().length()));
            for (int i=0; i<temps.size(); i++){
                variables.put(path.getPathVariables().get(i), temps.get(i).trim().replace("/", ""));
            }
        }
        return variables;
    }

}
